<template>
  <div class="cart">
    <h4>全部商品</h4>
    <!-- cart-main:购物车主体部分 -->
    <div class="cart-main">
      <!-- 头部标题 -->
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <!-- 购物车身体部分 -->
      <div class="cart-body">
        <!--ul代表一个商品-->
        <ul
          class="cart-list"
          v-for="(good, index) in cartInfoList"
          :key="good.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              :checked="good.isChecked == 1"
              @change="updateChecked(good, $event)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="good.imgUrl" />
            <div class="item-msg">{{ good.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ good.cartPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="minus(good)">-</a>
            <input
              type="text"
              :value="good.skuNum"
              class="itxt"
              @input="changeSkuNum(good, $event)"
            />
            <a href="javascript:void(0)" class="plus" @click="add(good)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ good.cartPrice * good.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="removeGood(good)">删除</a>
            <br />
            <a>移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" :checked="isChecked && cartInfoList.length>0 " @change="updateAllGoodChecked" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="removeAllCheckedGood">删除选中的商品</a>
        <a>移到我的关注</a>
        <a>清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ totalNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
//函数的节流
import throttle from "lodash/throttle";
//防抖
import debounce from "lodash/debounce";
//通过辅助函数获取用户购物车数据
export default {
  name: "ShopCart",
  //组件挂载完毕，获取一次购物车数据
  mounted() {
    //获取一次用户购物车数据
    this.getData();
  },
  computed: {
    ...mapGetters(["cartInfoList"]),
    //商品总个数
    totalNum() {
      //利用reduce计算用户购买商品的总个数----for循环也可以
      let totalNum = this.cartInfoList.reduce((pre, next) => {
        //三次执行: 第一次 pre 0   next: 1   结果1
        //         第二次 pre 1    next:2   结果3
        //         第三次 pre 3    next:16  结果19
        return pre + next.skuNum;
      }, 0);
      return totalNum;
    },
    //总价
    totalPrice() {
      return this.cartInfoList.reduce(
        (pre, next) => pre + next.skuNum * next.cartPrice,
        0
      );
    },
    //全选√不勾判断
    isChecked() {
      return this.cartInfoList.every((good) => good.isChecked === 1);
      //先把商品已经勾选的过滤出来
      // let arr = this.cartInfoList.filter(item=>{
      //     return item.isChecked ==1;
      // });
      // return arr.length===this.cartInfoList.length?true:false;
    },
  },
  methods: {
    //获取用户购物车数据的方法
    getData() {
      this.$store.dispatch("getUserCartList");
    },
    //商品数量加号回调
    async add(good) {
      let skuId = good.skuId;
      let skuNum = 1;
      //通知vuex发请求修改商品数量
      try {
        //修改商品成功以后
        await this.$store.dispatch("updateGoodSkuNum", { skuId, skuNum });
        //再次获取购物车修改以后数据
        this.getData();
      } catch (error) {
        //弹出提示信息
        alert(error.message);
      }
    },
    //商品数量减号回调
    minus: throttle(async function (good) {
      //商品的数量修改确实可以，保证商品数量个数大于1
      if (good.skuNum > 1) {
        let skuId = good.skuId;
        let skuNum = -1;
        //派发请求修改商品数量
        //通知vuex发请求修改商品数量
        try {
          //修改商品成功以后
          await this.$store.dispatch("updateGoodSkuNum", { skuId, skuNum });
          //再次获取购物车修改以后数据
          this.getData();
        } catch (error) {
          //弹出提示信息
          alert(error.message);
        }
      }
    }, 1000),
    //商品中间文本框的回调
    changeSkuNum: debounce(async function (good, event) {
      //如果用户输入内容非法:修改变化数值0，这个数值不能变
      //如果用户输入内容正常:16->21,变化后的数值 5    16->8,变化后的数值-8
      let userValue = event.target.value * 1;
      //携带参数
      let skuId = good.skuId;
      let skuNum = 0;
      if (isNaN(userValue) || userValue < 1) {
        //指定非法
        skuNum = 0;
      } else {
        //合法的携带变化数值:用户输入完的结果数值减去起始数值
        skuNum = Math.ceil(userValue) - good.skuNum;
      }
      //整理完毕参数再次发请求
      try {
        //修改商品成功以后
        await this.$store.dispatch("updateGoodSkuNum", { skuId, skuNum });
        //再次获取购物车修改以后数据
        this.getData();
      } catch (error) {
        //弹出提示信息
        alert(error.message);
      }
    }, 1000),

    //修改某一个商品勾选状态
    async updateChecked(good, e) {
      //商品ID
      let skuId = good.skuId;
      //勾选状态
      let isChecked = e.target.checked ? "1" : "0";
      try {
        //派发action通知vuex发请求，让服务器修改商品的勾选状态
        //修改商品状态成功以后
        await this.$store.dispatch("updateGoodChecked", { skuId, isChecked });
        //再次获取购物车最新的数据
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //删除某一个商品
    async removeGood(good) {
      try {
        //删除商品成功
        await this.$store.dispatch("removeGoodById", good.skuId);
        //再次获取购物车最新的数据
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //删除用户选中的全部商品
    //没有一次删除多个商品的接口，只有一次删一个！！！
    //需要保证:勾选商品有五个,这个五个都删除务必，在获取最新的购物车数据
    async removeAllCheckedGood() {
      //派发action通知vuex发请求
      try {
        //代表全部的勾选商品都删除成功以后
        await this.$store.dispatch("removeAllCheckedGood");
        //在获取购物车数据
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    //全选复选框的回调
    async updateAllGoodChecked(e){
       //获取全选复选框勾选状态数值
       let isChecked = e.target.checked?'1':'0';
       //派发action:当全部商品勾选状态修改完毕，再次获取购物车最新数据
      try {
        //保证全部商品勾选状态一次修改完毕
        await this.$store.dispatch('updateAllGoodChecked',isChecked);
        //再次获取购物车最新的数据
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    }
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 15%;
        }

        .cart-list-con2 {
          width: 35%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 10%;
        }

        .cart-list-con5 {
          width: 17%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>